package com.th.apicenter.tools;

import lombok.Data;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Data
public class MiTools {

    /**
     * sign = MD5(paramStr)
     * parmStr = sort_by_key 【 接口入参（key1value1key2value2） + ( signId_key + signId_value ) 】 + secretKey_value
     * sort_by_key 参数按照英文字母升序排序，signId 需要加入排序
     *
     * @return
     */
    public static String createSign(Map<String, String> originalMap, String secretKey) {
        // 按 Key 升序排序
        Map<String, String> sortedMap = originalMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldVal, newVal) -> oldVal,
                        LinkedHashMap::new
                ));

        StringBuffer sortByKey = new StringBuffer();
        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            sortByKey.append(entry.getKey() + entry.getValue());
        }

        //md5加密
        String md5Data = Md5Tools.md5(sortByKey.toString() + secretKey);
        return md5Data;
    }
}
